import { View } from '@tarojs/components'
import { chooseImage } from '@tarojs/taro'
import { SafeArea } from 'antd-mobile'
import HeadBox from '@/components/HeadBox'
import ChartBox from '@/components/ChartBox'
import style from './index.module.scss'
import classnames from 'classnames/bind'
import InputBox from '@/components/InputBox'
import { useDispatch, useSelector } from 'react-redux'
import { MessageType, infoType, setMessageList, getMessageListById, setMessageByIdUrl } from '@/store/MessageStore'
import useWebsocket from '@/hooks/useWebsocket'
import useSetToken from '@/hooks/useSetToken'
import useLoadServeInfo from '@/hooks/useLoadServeInfo'
import useLoadCustomerInfo from '@/hooks/useLoadCustomerInfo'
import { stateType } from '@/store'
import { useRef, useState } from 'react'
import useSendMsgSocket from '@/hooks/useSendMsgSocket'
import { ImageUpload } from '@/server'
import { createContext } from 'react'
import { nextTick } from 'process'
import { PullToRefresh } from 'antd-mobile'
import { PullStatus } from 'antd-mobile/es/components/pull-to-refresh'
import useLoadHistoryMessage from '@/hooks/useLoadHistoryMessage'
import timeFormater from "time-formater";
type OutContextType = {
  sendMessage: (data: infoType) => void,
  sendSystemMessage: (data: infoType) => void
  TransferToManualLabor: () => void
}
export const OutContext = createContext<OutContextType | undefined>(undefined)
//私有样式修改
const CBN = classnames.bind(style)
export default function Index() {
  const [servicetype, setservicetype] = useState<any>(null)
  const chartcontain = useRef<HTMLDivElement>(null)
  const MyChartBox = useRef<any>(null)
  useSetToken()

  //获取客户的数据
  useLoadCustomerInfo()
  //获取客户数据
  const { chatid, nickname, head } = useSelector((state: stateType) => state.CustomerInfoReducer)
  //获取服务者的信息
  const ServicerInfo = useSelector((state: stateType) => state.ServiceReducer)
  const dispatch = useDispatch()
  //获取历史数据
  const { loadHistoryMsg } = useLoadHistoryMessage(chatid, (id: string) => {
    const node = MyChartBox.current.ReturnLastMsgNode(id)
    node.scrollIntoView();
    console.log('返回最后的一个聊天数据内容', node)
  })
  //滚动到底部
  const scrolltoBottom = (stay = null) => {
    //滚动条到底效果
    if (stay === null) {
      nextTick(() => {
        if (!chartcontain || !chartcontain.current) return
        chartcontain.current.scrollTop = 9999999999
      })
    }
  }
  /**开启websocket服务 */
  const { sendMsg, closConnect } = useWebsocket('ws://172.19.190.143:8888/websocket', scrolltoBottom, () => {
    setservicetype(null)
  })

  //获取人工还是AI的数据
  useLoadServeInfo(servicetype,sendMsg,scrolltoBottom)
  //监听消息队列的变化 来给websocket发送数据
  useSendMsgSocket({ sendMsg })

  //发送文本信息啊
  const sendMessage = (info: infoType) => {
    const id = new Date().getTime() + '_local'
    let messagedata: MessageType = {
      id,
      head: head,
      nickname: nickname,
      sendid: chatid,
      time: timeFormater().format('YYYY-MM-DD HH:mm:ss'),
      info,
    }
    dispatch(setMessageList(messagedata))
    if (info.type === 'image') {
      ImageUpload(info.value, (progress) => {
        dispatch(getMessageListById({ id, loadingPercent: progress.progress }))
      }).then((res: any) => {
        dispatch(setMessageByIdUrl({ id, url: res.data }))
      })
    }
    scrolltoBottom()
  }

  //发送系统信息
  const sendSystemMessage = (info: infoType) => {
    const id = new Date().getTime() + '_local'
    let messagedata: MessageType = {
      id: id,
      head: ServicerInfo.head,
      nickname: ServicerInfo.nickname,
      sendid: ServicerInfo.chatid,
      time: timeFormater().format('YYYY-MM-DD HH:mm:ss'),
      info,
    }
    dispatch(setMessageList(messagedata))
    scrolltoBottom()
  }

  //发送图片信息
  const sendImage = () => {
    chooseImage({
      count: 1, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有，在H5浏览器端支持使用 `user` 和 `environment`分别指定为前后摄像头
      success: function (res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        var tempFilePaths = res.tempFilePaths[0]
        const info: infoType = {
          type: 'image',
          value: tempFilePaths,
          isSuccess: false,
          loadingPercent: 0
        }
        sendMessage(info)
      }
    })
  }

  //转人工进行服务
  const TransferToManualLabor = () => {
    sendSystemMessage({
      type: 'tips',
      value: '人工接入中,请稍后.....'
    })
    setservicetype(1)
    scrolltoBottom()
  }

  const statusRecord: Record<PullStatus, string> = {
    pulling: '用力拉',
    canRelease: '松开吧',
    refreshing: '玩命加载中...',
    complete: '好啦',
  }


  return (
    <View className={CBN('yunkefu')}>
      {/* {ServicerInfo.nickname} */}
      <HeadBox></HeadBox>
      <View className={CBN('chartcontain')} ref={chartcontain}>
        <OutContext.Provider value={{ sendMessage, sendSystemMessage, TransferToManualLabor }}>
          <PullToRefresh
            renderText={status => {
              return <div>{statusRecord[status]}</div>
            }}
            onRefresh={async () => {
              loadHistoryMsg()
            }}>
            <ChartBox ref={MyChartBox as any}>

            </ChartBox>
          </PullToRefresh>
        </OutContext.Provider>
      </View>
      <InputBox sendMessage={sendMessage} sendImage={sendImage}></InputBox>
      {/* 底部安全区 */}
      <div style={{ background: '#ffcfac' }}>
        <SafeArea position='bottom' />
      </div>
    </View>
  )
}
